
// 导入数据库连接
const db = require('../config/db');

// 获取用户公告列表（支持分页）
exports.getAnnouncements = async (req, res) => {
  try {
    console.log(`[${new Date().toLocaleString()}] [INFO] 开始处理用户公告列表请求`);
    const { page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    console.log(`[${new Date().toLocaleString()}] [INFO] 获取用户公告列表请求参数: 页码=${currentPage}, 每页数量=${itemsPerPage}, 偏移量=${offset}`);

    // 构建公告数据SQL查询（只包含前端需要的字段）
    let sql = `
      SELECT a.announcement_id, a.title, a.content, a.is_top, a.status, a.view_count, 
             DATE_FORMAT(a.publish_time, '%Y-%m-%d %H:%i:%s') AS publish_time, 
             DATE_FORMAT(a.expire_time, '%Y-%m-%d %H:%i:%s') AS expire_time, 
             u.username AS author_name
      FROM announcements a
      LEFT JOIN users u ON a.author_id = u.user_id
      WHERE a.status = 1 AND a.publish_time <= NOW()
      ORDER BY a.is_top DESC, a.publish_time DESC
      LIMIT ? OFFSET ?
    `;

    // 构建总数量SQL查询
    let countSql = `
      SELECT COUNT(*) as total
      FROM announcements
      WHERE status = 1 AND publish_time <= NOW()
    `;

    // 执行查询
    console.log(`[${new Date().toLocaleString()}] [INFO] 执行用户公告列表查询SQL`);
    const [announcements] = await db.query(sql, [itemsPerPage, offset]);
    console.log(`[${new Date().toLocaleString()}] [INFO] 用户公告列表查询完成，获取到 ${announcements.length} 条记录`);
    
    console.log(`[${new Date().toLocaleString()}] [INFO] 执行用户公告总数查询SQL`);
    const [[{ total }]] = await db.query(countSql);
    console.log(`[${new Date().toLocaleString()}] [INFO] 用户公告总数查询完成，总数=${total}`);

    // 计算总页数
    const totalPages = Math.ceil(total / itemsPerPage);

    console.log(`[${new Date().toLocaleString()}] [INFO] 用户公告列表查询结果: 总数=${total}, 页数=${totalPages}`);

    console.log(`[${new Date().toLocaleString()}] [INFO] 用户公告列表请求处理完成，准备返回数据`);
    res.json({
      success: true,
      data: {
        announcements,
        pagination: {
          currentPage,
          itemsPerPage,
          total,
          totalPages
        }
      }
    });
  } catch (error) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 获取用户公告列表失败: ${error.message}`);
    res.status(500).json({
      success: false,
      error: '获取公告列表失败'
    });
  }
};

// 获取管理员公告列表（支持筛选和分页）
exports.getAdminAnnouncements = async (req, res) => {
  try {
    console.log(`[${new Date().toLocaleString()}] [INFO] 开始处理管理员公告列表请求`);
    const { page = 1, pageSize = 10, status = '-1', startDate, endDate, keyword } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    console.log(`[${new Date().toLocaleString()}] [INFO] 获取管理员公告列表请求参数: 页码=${currentPage}, 每页数量=${itemsPerPage}, 偏移量=${offset}, 状态=${status}, 开始日期=${startDate}, 结束日期=${endDate}, 关键字=${keyword}`);

    // 构建SQL查询条件
    let whereClause = [];
    let queryParams = [];

    if (status !== '-1') {
      whereClause.push('a.status = ?');
      queryParams.push(status);
    }

    if (startDate) {
      whereClause.push('a.created_at >= ?');
      queryParams.push(startDate);
    }

    if (endDate) {
      whereClause.push('a.created_at <= ?');
      queryParams.push(`${endDate} 23:59:59`);
    }

    if (keyword) {
      whereClause.push('(a.title LIKE ? OR a.content LIKE ?)');
      queryParams.push(`%${keyword}%`, `%${keyword}%`);
    }

    // 构建基础SQL
    const baseWhere = whereClause.length > 0 ? 'WHERE ' + whereClause.join(' AND ') : '';
    const limitOffset = 'LIMIT ? OFFSET ?';
    queryParams.push(itemsPerPage, offset);

    // 构建公告数据SQL查询
    let sql = `
      SELECT a.announcement_id, a.title, a.content, a.author_id, a.is_top, a.status, a.view_count, 
             DATE_FORMAT(a.publish_time, '%Y-%m-%d %H:%i:%s') AS publish_time, 
             DATE_FORMAT(a.expire_time, '%Y-%m-%d %H:%i:%s') AS expire_time, 
             DATE_FORMAT(a.created_at, '%Y-%m-%d %H:%i:%s') AS created_at, 
             DATE_FORMAT(a.updated_at, '%Y-%m-%d %H:%i:%s') AS updated_at, 
             u.username AS author_name
      FROM announcements a
      LEFT JOIN users u ON a.author_id = u.user_id
      ${baseWhere}
      ORDER BY a.is_top DESC, a.created_at DESC
      ${limitOffset}
    `;

    // 构建总数量SQL查询
    let countSql = `
      SELECT COUNT(*) as total
      FROM announcements a
      ${baseWhere}
    `;

    // 执行查询
    console.log(`[${new Date().toLocaleString()}] [INFO] 执行管理员公告列表查询SQL`);
    const [announcements] = await db.query(sql, queryParams);
    console.log(`[${new Date().toLocaleString()}] [INFO] 管理员公告列表查询完成，获取到 ${announcements.length} 条记录`);
    
    // 调整查询参数以获取总数（移除limit和offset参数）
    const countParams = queryParams.slice(0, -2);
    console.log(`[${new Date().toLocaleString()}] [INFO] 执行管理员公告总数查询SQL`);
    const [[{ total }]] = await db.query(countSql, countParams);
    console.log(`[${new Date().toLocaleString()}] [INFO] 管理员公告总数查询完成，总数=${total}`);

    // 计算总页数
    const totalPages = Math.ceil(total / itemsPerPage);

    console.log(`[${new Date().toLocaleString()}] [INFO] 管理员公告列表查询结果: 总数=${total}, 页数=${totalPages}`);

    console.log(`[${new Date().toLocaleString()}] [INFO] 管理员公告列表请求处理完成，准备返回数据`);
    res.json({
      success: true,
      data: {
        announcements,
        pagination: {
          currentPage,
          itemsPerPage,
          total,
          totalPages
        }
      }
    });
  } catch (error) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 获取管理员公告列表失败: ${error.message}`);
    res.status(500).json({
      success: false,
      error: '获取公告列表失败'
    });
  }
};

// 获取公告详情
exports.getAnnouncementDetail = async (req, res) => {
  try {
    console.log(`[${new Date().toLocaleString()}] [INFO] 开始处理公告详情请求`);
    const { id } = req.params;

    console.log(`[${new Date().toLocaleString()}] [INFO] 获取公告详情请求参数: 公告ID=${id}`);

    // 查询公告详情
    const sql = `
      SELECT a.announcement_id, a.title, a.content, a.is_top, a.status, a.view_count, 
             DATE_FORMAT(a.publish_time, '%Y-%m-%d %H:%i:%s') AS publish_time, 
             DATE_FORMAT(a.expire_time, '%Y-%m-%d %H:%i:%s') AS expire_time, 
             DATE_FORMAT(a.created_at, '%Y-%m-%d %H:%i:%s') AS created_at, 
             DATE_FORMAT(a.updated_at, '%Y-%m-%d %H:%i:%s') AS updated_at, 
             u.username AS author_name
      FROM announcements a
      LEFT JOIN users u ON a.author_id = u.user_id
      WHERE a.announcement_id = ?
    `;

    console.log(`[${new Date().toLocaleString()}] [INFO] 执行公告详情查询SQL: 公告ID=${id}`);
    const [announcements] = await db.query(sql, [id]);
    console.log(`[${new Date().toLocaleString()}] [INFO] 公告详情查询完成，结果数量=${announcements.length}`);

    if (announcements.length === 0) {
      return res.status(404).json({
        success: false,
        error: '公告不存在'
      });
    }

    // 增加查看次数（仅当公告已发布时）
    if (announcements[0].status === 1 && new Date(announcements[0].publish_time) <= new Date()) {
      console.log(`[${new Date().toLocaleString()}] [INFO] 更新公告查看次数: 公告ID=${id}`);
      await db.query('UPDATE announcements SET view_count = view_count + 1 WHERE announcement_id = ?', [id]);
      console.log(`[${new Date().toLocaleString()}] [INFO] 公告查看次数更新成功`);
    }

    console.log(`[${new Date().toLocaleString()}] [INFO] 公告详情查询成功: 公告ID=${id}`);

    console.log(`[${new Date().toLocaleString()}] [INFO] 公告详情请求处理完成，准备返回数据`);
    res.json({
      success: true,
      data: announcements[0]
    });
  } catch (error) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 获取公告详情失败: ${error.message}`);
    res.status(500).json({
      success: false,
      error: '获取公告详情失败'
    });
  }
};

// 创建公告
exports.createAnnouncement = async (req, res) => {
  try {
    console.log(`[${new Date().toLocaleString()}] [INFO] 开始处理创建公告请求`);
    const { title, content, is_top = 0, expire_time, status = 0 } = req.body;
    const author_id = req.user?.id; // 安全获取用户ID
    console.log(`[${new Date().toLocaleString()}] [DEBUG] 当前用户ID: ${author_id}`);
    if (!author_id) {
      console.log(`[${new Date().toLocaleString()}] [ERROR] 用户未登录或身份验证失败`);
      return res.status(401).json({
        success: false,
        error: '用户未登录或身份验证失败'
      });
    }

    console.log(`[${new Date().toLocaleString()}] [INFO] 创建公告请求参数: 标题=${title}, 是否置顶=${is_top}, 过期时间=${expire_time}, 状态=${status}`);

    // 验证必填字段
    if (!title || !content) {
      return res.status(400).json({
        success: false,
        error: '标题和内容是必填项'
      });
    }

    // 处理发布时间
    const publish_time = status === 1 ? new Date() : null;

    // 处理过期时间格式（转换为MySQL支持的datetime格式）
    let formattedExpireTime = null;
    if (expire_time) {
      const date = new Date(expire_time);
      formattedExpireTime = date.toISOString().slice(0, 19).replace('T', ' ');
    }

    // 构建SQL
    const sql = `
      INSERT INTO announcements (title, content, author_id, is_top, status, publish_time, expire_time)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `;

    const params = [title, content, author_id, is_top, status, publish_time, formattedExpireTime];

    console.log(`[${new Date().toLocaleString()}] [INFO] 执行创建公告SQL`);
    const [result] = await db.query(sql, params);
    console.log(`[${new Date().toLocaleString()}] [INFO] 创建公告成功，公告ID=${result.insertId}`);

    console.log(`[${new Date().toLocaleString()}] [INFO] 创建公告请求处理完成，准备返回数据`);
    res.status(201).json({
      success: true,
      message: status === 1 ? '公告发布成功' : '公告保存为草稿成功',
      data: {
        announcement_id: result.insertId
      }
    });
  } catch (error) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 创建公告失败: ${error.message}`);
    res.status(500).json({
      success: false,
      error: '创建公告失败'
    });
  }
};

// 更新公告
exports.updateAnnouncement = async (req, res) => {
  try {
    console.log(`[${new Date().toLocaleString()}] [INFO] 开始处理更新公告请求`);
    const { id } = req.params;
    const { title, content, is_top = 0, expire_time } = req.body;

    console.log(`[${new Date().toLocaleString()}] [INFO] 更新公告请求参数: 公告ID=${id}, 标题=${title}, 是否置顶=${is_top}, 过期时间=${expire_time}`);

    // 验证必填字段
    if (!title || !content) {
      return res.status(400).json({
        success: false,
        error: '标题和内容是必填项'
      });
    }

    // 检查公告是否存在
    const checkSql = 'SELECT * FROM announcements WHERE announcement_id = ?';
    const [announcements] = await db.query(checkSql, [id]);

    if (announcements.length === 0) {
      return res.status(404).json({
        success: false,
        error: '公告不存在'
      });
    }

    // 检查公告状态（已撤回的公告不能修改）
    if (announcements[0].status === 2) {
      return res.status(400).json({
        success: false,
        error: '已撤回的公告不能修改'
      });
    }

    // 处理过期时间格式（转换为MySQL支持的datetime格式）
    let formattedExpireTime = null;
    if (expire_time) {
      const date = new Date(expire_time);
      formattedExpireTime = date.toISOString().slice(0, 19).replace('T', ' ');
    }

    // 构建SQL
    const sql = `
      UPDATE announcements
      SET title = ?, content = ?, is_top = ?, expire_time = ?
      WHERE announcement_id = ?
    `;

    const params = [title, content, is_top, formattedExpireTime, id];

    console.log(`[${new Date().toLocaleString()}] [INFO] 执行更新公告SQL: 公告ID=${id}`);
    await db.query(sql, params);
    console.log(`[${new Date().toLocaleString()}] [INFO] 更新公告成功: 公告ID=${id}`);

    console.log(`[${new Date().toLocaleString()}] [INFO] 更新公告请求处理完成，准备返回数据`);
    res.json({
      success: true,
      message: '公告更新成功'
    });
  } catch (error) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 更新公告失败: ${error.message}`);
    res.status(500).json({
      success: false,
      error: '更新公告失败'
    });
  }
};

// 发布公告
exports.publishAnnouncement = async (req, res) => {
  try {
    console.log(`[${new Date().toLocaleString()}] [INFO] 开始处理发布公告请求`);
    const { id } = req.params;

    console.log(`[${new Date().toLocaleString()}] [INFO] 发布公告请求参数: 公告ID=${id}`);

    // 检查公告是否存在
    const checkSql = 'SELECT * FROM announcements WHERE announcement_id = ?';
    const [announcements] = await db.query(checkSql, [id]);

    if (announcements.length === 0) {
      return res.status(404).json({
        success: false,
        error: '公告不存在'
      });
    }

    // 检查公告状态
    if (announcements[0].status !== 0) {
      return res.status(400).json({
        success: false,
        error: '只有草稿状态的公告才能发布'
      });
    }

    // 构建SQL
    const sql = `
      UPDATE announcements
      SET status = 1, publish_time = NOW()
      WHERE announcement_id = ?
    `;

    console.log(`[${new Date().toLocaleString()}] [INFO] 执行发布公告SQL: 公告ID=${id}`);
    await db.query(sql, [id]);
    console.log(`[${new Date().toLocaleString()}] [INFO] 发布公告成功: 公告ID=${id}`);

    console.log(`[${new Date().toLocaleString()}] [INFO] 发布公告请求处理完成，准备返回数据`);
    res.json({
      success: true,
      message: '公告发布成功'
    });
  } catch (error) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 发布公告失败: ${error.message}`);
    res.status(500).json({
      success: false,
      error: '发布公告失败'
    });
  }
};

// 撤回公告
exports.recallAnnouncement = async (req, res) => {
  try {
    console.log(`[${new Date().toLocaleString()}] [INFO] 开始处理撤回公告请求`);
    const { id } = req.params;

    console.log(`[${new Date().toLocaleString()}] [INFO] 撤回公告请求参数: 公告ID=${id}`);

    // 检查公告是否存在
    const checkSql = 'SELECT * FROM announcements WHERE announcement_id = ?';
    const [announcements] = await db.query(checkSql, [id]);

    if (announcements.length === 0) {
      return res.status(404).json({
        success: false,
        error: '公告不存在'
      });
    }

    // 检查公告状态
    if (announcements[0].status !== 1) {
      return res.status(400).json({
        success: false,
        error: '只有已发布状态的公告才能撤回'
      });
    }

    // 构建SQL
    const sql = `
      UPDATE announcements
      SET status = 2
      WHERE announcement_id = ?
    `;

    console.log(`[${new Date().toLocaleString()}] [INFO] 执行撤回公告SQL: 公告ID=${id}`);
    await db.query(sql, [id]);
    console.log(`[${new Date().toLocaleString()}] [INFO] 撤回公告成功: 公告ID=${id}`);

    console.log(`[${new Date().toLocaleString()}] [INFO] 撤回公告请求处理完成，准备返回数据`);
    res.json({
      success: true,
      message: '公告撤回成功'
    });
  } catch (error) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 撤回公告失败: ${error.message}`);
    res.status(500).json({
      success: false,
      error: '撤回公告失败'
    });
  }
};

// 删除公告
exports.deleteAnnouncement = async (req, res) => {
  try {
    console.log(`[${new Date().toLocaleString()}] [INFO] 开始处理删除公告请求`);
    const { id } = req.params;

    console.log(`[${new Date().toLocaleString()}] [INFO] 删除公告请求参数: 公告ID=${id}`);

    // 检查公告是否存在
    const checkSql = 'SELECT * FROM announcements WHERE announcement_id = ?';
    const [announcements] = await db.query(checkSql, [id]);

    if (announcements.length === 0) {
      return res.status(404).json({
        success: false,
        error: '公告不存在'
      });
    }

    // 检查公告状态（已发布的公告不能删除）
    if (announcements[0].status === 1) {
      return res.status(400).json({
        success: false,
        error: '已发布的公告不能删除，请先撤回'
      });
    }

    // 构建SQL
    const sql = 'DELETE FROM announcements WHERE announcement_id = ?';

    console.log(`[${new Date().toLocaleString()}] [INFO] 执行删除公告SQL: 公告ID=${id}`);
    await db.query(sql, [id]);
    console.log(`[${new Date().toLocaleString()}] [INFO] 删除公告成功: 公告ID=${id}`);

    console.log(`[${new Date().toLocaleString()}] [INFO] 删除公告请求处理完成，准备返回数据`);
    res.json({
      success: true,
      message: '公告删除成功'
    });
  } catch (error) {
    console.error(`[${new Date().toLocaleString()}] [ERROR] 删除公告失败: ${error.message}`);
    res.status(500).json({
      success: false,
      error: '删除公告失败'
    });
  }
};